package com.ocom.accesservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ocom.accesservice.dao.IDaoDeptInfo;
import com.ocom.accesservice.service.DeptInfoService;
import com.ocom.common.entity.access.EntityDeptInfo;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.mysql.aspect.DataSourceAspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DeptInfoServiceImpl extends ServiceImpl<IDaoDeptInfo, EntityDeptInfo> implements DeptInfoService {

    @Autowired
    private IDaoDeptInfo iDaoDeptInfo;

    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "comId",isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public EntityDeptInfo selectDeptName(Long comId, long deptId) {
        QueryWrapper<EntityDeptInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("com_id",comId);
        wrapper.eq("dept_id",deptId);
        wrapper.last("limit 1");
        return iDaoDeptInfo.selectOne(wrapper);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "companyId",isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityDeptInfo> getDeptList(Long companyId, Long deptId) {
        QueryWrapper<EntityDeptInfo> querys = Wrappers.query();
        querys.eq("com_id",companyId);
        if(deptId==null ||  deptId<=0l){
            return this.list(querys);
        }else{
            List<EntityDeptInfo> list=  this.list(querys);
            List<EntityDeptInfo> list2=new ArrayList<>();
            List<Long> ins= new ArrayList<>();
            ins.add(deptId);
            return loop(list,list2,ins);
        }
    }

    //递归操作
    //循环出有用部门树
    public List<EntityDeptInfo>  loop(List<EntityDeptInfo> list1, List<EntityDeptInfo> list2, List<Long> ins){
        int before = ins.size();
        for (EntityDeptInfo entityDeptInfo:list1){
            if(ins.contains(entityDeptInfo.getDeptId()) || ins.contains(entityDeptInfo.getParentDeptId())){
                List<Object> newList = list2.stream().map(EntityDeptInfo::getDeptId).collect(Collectors.toList());
                if(!newList.contains(entityDeptInfo.getDeptId())){
                    list2.add(entityDeptInfo);
                    ins.add(entityDeptInfo.getDeptId());
                }
            }
        }
        int after = ins.size();
        //无新增 返回
        if(before==after){
            return  list2;
        }else{
            return loop(list1,list2,ins);
        }
    }
}
